# -*- coding: utf-8 -*-

from pathlib import Path
from application.settings import BASE_DIR
from core.viewset import CustomModelViewSet
from rest_framework.decorators import action
from django.http import FileResponse
from .models import OfflineDocument
from .serializers import OfflineDocumentSerializer
from .filters import OfflineDocumentFilterSet


class OfflineDocumentViewSet(CustomModelViewSet):
    """
    离线文件接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """

    queryset = OfflineDocument.objects.all()
    serializer_class = OfflineDocumentSerializer
    filterset_class = OfflineDocumentFilterSet

    @action(detail=False, methods=["POST"])
    def download(self, request, pk=None, *args, **kwargs):
        file_name = request.data.get("file")
        file_path = BASE_DIR.joinpath(Path(file_name).relative_to("/"))
        response = FileResponse(open(file_path, "rb"))
        return response
